﻿using ProTrack.Dto;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace ProTrack.Api.Helper
{

    /// <summary>
    /// 异常辅助类
    /// </summary>
    public class ExceptionHelper
    {

        /// <summary>
        /// 获取异常信息
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public static ExceptionDetailsDto GetExceptionDetails(Exception ex)
        {

            StackTrace stackTrace = new StackTrace(ex, true);
            StackFrame frame = stackTrace.GetFrame(0);
            // 行号
            int lineNumber = frame.GetFileLineNumber();


            // 异常消息
            string exceptionMessage = ex.Message;

            // 异常根消息
            string rootExceptionMessage = ex.GetBaseException().Message;

            // 栈轨迹
            string stackTraceStr = ex.StackTrace;

            // 异常发生的类全名
            string className = ex.TargetSite.ReflectedType.FullName;

            // 异常发生的类文件
            string fileName = ex.TargetSite.ReflectedType.Assembly.Location;


            // 方法名称
            string methodName = ex.TargetSite.Name;

            // 参数
            string parameterInfo = "";
            foreach (var parameter in ex.TargetSite.GetParameters())
            {
                parameterInfo += parameter.ParameterType.Name + " " + parameter.Name + ", ";
            }
            if (parameterInfo.Length > 0)
            {
                parameterInfo = parameterInfo.Substring(0, parameterInfo.Length - 2);
            }

            return new ExceptionDetailsDto
            {
                ExceptionTime= DateTime.Now,
                ExceptionMessage= exceptionMessage,
                RootExceptionMessage= rootExceptionMessage,
                StackTraceStr= stackTraceStr,
                ClassName= className,
                FileName= fileName,
                LineNumber= lineNumber,
                MethodName= methodName,
                ParameterInfo= parameterInfo
            };
        }
    }
}
